package com.yinxing.framework.shiro.filter;

import com.yinxing.framework.shiro.exception.RequiresRolesException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;

/**
 * 当前用户必须拥有相应角色
 * 判断条件:subject.hasAllRoles(roles);
 */
public class RequiresRolesFilter extends RolesAuthorizationFilter {

    private final static String ROLES_KEY = RequiresRolesFilter.class.getName() + "." + "ROLES_KEY";

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            return true;
        }

        request.setAttribute(ROLES_KEY, rolesArray);

        Set<String> roles = CollectionUtils.asSet(rolesArray);
        return subject.hasAllRoles(roles);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        String[] rolesArray = (String[]) request.getAttribute(ROLES_KEY);
        String msg = "用户不具备所需角色" + Arrays.toString(rolesArray);
        throw new RequiresRolesException(msg);
    }
}
